package crm8000.services

import crm8000.Models.CustomerCategory;
import crm8000.Models.PWBill;
import crm8000.Models.Payables;
import crm8000.Models.PayablesDetail;
import crm8000.Models.PwPayment;
import crm8000.Models.SupplierCategory;
import crm8000.Models.User;
import crm8000.helper.Result
import crm8000.viewModels.PayablesDetailVM
import crm8000.viewModels.PayablesVM
import grails.transaction.Transactional

/**
 * 应付Service
 *
 */
@Transactional
class PayService {

	UserService userService

	def categoryList(String id) {
		if (id == "customer") {
			return CustomerCategory.listOrderByCode()
		} else {
			return SupplierCategory.listOrderByCode()
		}
	}

	def payList(params) {
		def caType = params.caType
		def categoryId = params.categoryId

		String hql
		if (caType == "supplier") {
			hql = ''' select p.id as id, c.code as code, c.name as name, p.payMoney as payMoney,
							p.actMoney as actMoney, p.balanceMoney as balanceMoney, c.id as caId
						from crm8000.Models.Payables as p , crm8000.Models.Supplier as c
						where p.caId = c.id and c.category.id = :categoryId
						order by c.code asc
					'''
		} else {
			hql = ''' select p.id as id, c.code as code, c.name as name, p.rvMoney as payMoney,
							p.actMoney as actMoney, p.balanceMoney as balanceMoney, c.id as caId
						from crm8000.Models.Payables as p , crm8000.Models.Customer as c
						where p.caId = c.id and c.category.id = :categoryId
						order by c.code asc
					'''
		}

		def result = []

		Payables.executeQuery(hql, [categoryId: categoryId], [max: params.limit, offset: params.start]).each {
			result.add(new PayablesVM(id: it[0], code: it[1],
			name: it[2], payMoney: it[3], actMoney: it[4],
			balanceMoney: it[5], caId: it[6]))
		}

		return result
	}

	def payListTotalCount(params) {
		def caType = params.caType
		def categoryId = params.categoryId

		String hql
		if (caType == "supplier") {
			hql = ''' select count(*)
						from crm8000.Models.Payables as p, crm8000.Models.Supplier as c
						where p.caId = c.id and c.category.id = :categoryId
					'''
		} else {
			hql = ''' select count(*)
						from crm8000.Models.Payables as p, crm8000.Models.Customer as c
						where p.caId = c.id and c.category.id = :categoryId
					'''
		}

		def data = Payables.executeQuery(hql, [categoryId: categoryId])

		return data[0]
	}

	def payDetailList(params) {
		def caType = params.caType
		def caId = params.caId

		def result = []

		def data = PayablesDetail.createCriteria().list {
			eq("caType", caType)
			eq("caId", caId)
			order "refNumber", "desc"
		}

		data.each {
			def vm = new PayablesDetailVM()
			vm.id = it.id
			vm.refType = it.refType
			vm.refNumber = it.refNumber
			vm.actMoney = it.actMoney
			vm.payMoney = it.payMoney
			vm.balanceMoney = it.balanceMoney

			if (it.refType == "采购入库") {
				def bill = PWBill.findByRef(it.refNumber)
				if (bill) {
					vm.bizDT = bill.bizDT.format("yyyy-MM-dd")
				}
			}
			result.add(vm)
		}

		return result
	}

	def payDetailListTotalCount(params) {
		def caType = params.caType
		def caId = params.caId

		return 	PayablesDetail.createCriteria().get {
			projections { count("id") }
			eq("caType", caType)
			eq("caId", caId)
		}
	}

	def payRecordList(params) {
		def refType = params.refType
		def refNumber = params.refNumber

		if (refType == "采购入库"){
			return PwPayment.createCriteria().list(max: params.limit, offset: params.start) {
				pwBill { eq ("ref", refNumber) }
				order "bizDate", "desc"
				order "dateCreated", "desc"
			}
		}
		else {
			return []
		}
	}

	def payRecordListTotalCount(params) {
		def refType = params.refType
		def refNumber = params.refNumber

		if (refType == "采购入库"){
			return PwPayment.createCriteria().get {
				projections { count("id")}
				pwBill { eq ("ref", refNumber) }
			}
		}
		else {
			return 0
		}
	}

	def addPayment(params) {
		def refType = params.refType
		def refNumber = params.refNumber

		def actMoney = params.actMoney.toBigDecimal()

		def bizDate = Date.parse("yyyy-MM-dd", params.bizDT)

		if (refType == "采购入库") {
			def bill = PWBill.findByRef(refNumber)
			if (!bill) {
				return new Result(success:false, msg: "单号为${refNumber}的采购入库单不存在")
			}

			def bizUser = User.get(params.bizUserId)
			if (!bizUser) {
				return new Result(success: false, msg: "收款人不存在")
			}

			def payDetail = PayablesDetail.createCriteria().get {
				eq "refType", refType
				eq "refNumber", refNumber
			}
			if (!payDetail) {
				return new Result(success: false, msg: "应付账款明细账记录不存在，请联系系统管理员")
			}
			def pay = Payables.createCriteria().get {
				eq "caId", payDetail.caId
				eq "caType", payDetail.caType
			}
			if (!pay) {
				return new Result(success: false, msg: "应付账款记录不存在，请联系系统管理员")
			}

			def rec = new PwPayment()
			rec.actMoney = actMoney
			rec.bizDate = bizDate
			rec.inputUser = userService.loginUser
			rec.remark = params.remark
			rec.payUser = bizUser
			rec.pwBill = bill

			rec.save()

			// 修改应收账款已收和余额
			pay.actMoney += rec.actMoney
			pay.balanceMoney = pay.payMoney - pay.actMoney
			pay.save()

			payDetail.actMoney += rec.actMoney
			payDetail.balanceMoney = payDetail.payMoney - payDetail.actMoney
			payDetail.save()

			return new Result(success: true, id: rec.id)
		}

		return new Result(success: false, msg: "TODO")
	}

	def refreshPayInfo(id) {
		return Payables.get(id)
	}

	def refreshPayDetailInfo(id) {
		return PayablesDetail.get(id)
	}
}